<template>
<!-- 纹理 -->
    <canvas id="canvas"></canvas>
</template>



<script setup lang="ts">
  import {onMounted} from "vue";
  import RenderContext from "@/views/cg/lib/RenderContext.ts";
  import {Model, shape} from "@/views/cg/lib";
  import { Mat4 , multiply4 } from '../lib/matrix'
  import gui from "@/views/cg/lib/gui";

  onMounted(()=>{
    let gl = RenderContext.getGL()
    const mesh = shape.d3_cube3(true, false, true)
    const model = new Model(mesh)
    // 算分辨率 给透视矩阵用的
    const aspect = gl.canvas.width/gl.canvas.height;
    let angle = Math.PI * 0.3;
    // 控制面板
    let controle = {
      light_x:0.0, //
      light_y:0.0, //
      light_z:-1.0 //
    }

    gui.add(controle, 'light_x').min(-5).max(5).step(0.1).name('light_x').onChange((value)=>{})
    gui.add(controle, 'light_y').min(-5).max(5).step(0.1).name('light_y').onChange((value)=>{})
    gui.add(controle, 'light_z').min(-5).max(5).step(0.1).name('light_z').onChange((value)=>{})

    function draw() {
      gl.enable(gl.DEPTH_TEST)
      gl.depthFunc(gl.LEQUAL)
      gl.clearDepth(1.0)
      gl.viewport(0.0, 0.0, canvas.width, canvas.height)
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

      // 创建世界坐标
      const mat4 = new Mat4()
      model.setWorldMatrix(mat4
        // .scale(1,-1,1)
        // 让立方体转起来
        .rotate(0,angle,0)
        .translate(0, 0, -2)
        .getMatrix()
      )

      const camera = [0,0,3]
      model.setMatrixUniform(
        'u_worldview',
        new Mat4()
          .lookAt(...camera,0,0,0)
          .perspective(Math.PI*0.5, aspect, 1.0, 1000)
          .getMatrix()
      )

      model.setVectorUniform('u_light', [controle.light_x, controle.light_y, controle.light_z])
      model.setVectorUniform('u_camera', camera)

      angle += 0.01
      model.updateMatrix()
      model.draw()
      requestAnimationFrame(draw)
    }
    draw()
  })
</script>

<style scoped lang="scss">
#canvas{
  width: 100%;
  height: 100%;
  display: block;
}
</style>
